import axios from "axios";
import {Message} from "element-ui";
import router from "@/router";
import store from '@/store'

//响应拦截器不显示成功信息url
const listUrl = ["api/captcha.png"]

//请求拦截器
axios.interceptors.request.use(config=>{
    if (sessionStorage.getItem("token_login")){
        config.headers["Authorization"]=sessionStorage.getItem("token_login")
    }
    return config;
},error => {
    console.log(error)
})

// 响应拦截器
axios.interceptors.response.use(
    (success) => {
        if (success.status && success.status === 200) {
            let code = success.data.code;
            if (code === 5001){
                //清除token和user信息
                sessionStorage.removeItem("token_login")
                sessionStorage.removeItem("user")
                //清除菜单列表
                store.commit("initRouters",[])
                router.replace("/")
                return
            }
            if (code === 5000 || code === 4001 || code === 4003) {
                Message.error({message: success.data.message})
                if (success.data.message)
                return;
            }
            if (success.data.message) {
                //拦截有消息但不用消息提示框的路径
                for (let i=0;i<listUrl.length;i++){
                    if (success.config.url.startsWith(listUrl[i])){
                        return success;
                    }
                }
                Message.success({message: success.data.message})
            }
            return success;
        }
    }, error => {
        let sta = error.code;
        if (sta === 504 || sta === 404) {
            Message.error({message: "服务器被吃了"})
        } else if (sta === 403) {
            Message.error({message: "权限不足，请联系管理员"})
        } else if (sta === 401) {
            Message.error({message: "未登录，请登录！"})
            router.replace('/')
        } else {
            Message.error({message: "未知错误"})
        }
        return;
    })

let prefix = '';
export const postRequest = (url, params) => {
    return axios({
        method: "post",
        url: `${prefix}${url}`,
        data: params
    })
}

export const getRequest = (url, params) => {
    return axios({
        method: "get",
        url: `${prefix}${url}`,
        data: params
    })
}

export const putRequest = (url, params) => {
    return axios({
        method: "put",
        url: `${prefix}${url}`,
        data: params
    })
}

export const deleteRequest = (url, params) => {
    return axios({
        method: "delete",
        url: `${prefix}${url}`,
        data: params
    })
}